###########################################
#  Primary Divisions: How Voters Evaluate Policy and Group Differences in Intra-Party Contests
#   - Forthcoming at The Journal of Politics
#   - Henderson et al 2021
#
###########################################
#  - code by S. Goggin & J. Henderson
########################################################
# This file produces figures for candidate choice, measuring heterogeneous marginal effects
########################################################

#dirs="~/Dropbox/replication0/"
#dirs should be set here or in runR.R

rm(list=ls()[which(ls()!='dirs')])
library(ggplot2)
library(stringr)
library(Rcpp)
# messy function to reorder by some estimate value
lableOrder=function(xmat,labels,label.groups,omits,o.column){

	# denote which label is to be omitted on the label
	for(i in 1:length(omits)){
		labels[which(labels==omits[i])]=paste('omit',labels[which(labels==omits[i])],sep='_')
	}

	# break groups into levels
	un_group=unique(label.groups)

	# this is the item to sort on, typically global or independent
	xm=xmat[,o.column]

	# vector which will contain row order
	xo=1:length(xm)

	# rearranging roworder within level
	for(j in 1:length(un_group)){
		ix=which(label.groups==un_group[j])
		if(length(ix)>2){
			ix=ix[!grepl(labels[ix],pattern='omit')]
			xo[ix]=xo[ix][order(xm[ix])]
		}
	}
	return(xmat[xo,])
}

reOrder=function(x,o){
	ix=array(NA,nrow(x))
	for(i in 1:length(o)){
		ix[i]=which(x$iv_order==o[i])
	}
	return(x[ix,])
}

library(car)

setwd(dirs)
load("data/cces_stacked_unmatched.Rdata")
load('data/data_matrix_scored.Rdata')
scored=read.csv('data/candidate_matrix.csv')

###########################################
###########################################
# ATTENTION SCREENERS :: HELP ASSESS INATTENATIVENESS => CROSS-PRESSURE OR MIXED UP
###########################################
###########################################
# 1. differenes in attention for cross-pressure on 50-50
# 2. differenes in attention for cross-pressure on 25-75
# 3. differenes in attention for 'cross-pressure' on each issue, i.e.,
#    - a) out-party attitude on each issue
#    - b) quantile of each summary score
# 4. differences in attention for 'cross-pressure' on issues overall, i.e.,
#    - a) add up # of issues at 0 or out-party side
# 5. differenes in attention for cross-pressure on 25-25 split, most/least consistent
library(car)

###########################################
###Then, produce models w/ Clustered SEs

#Function from: http://scholar.byu.edu/jgubler/book/clustered-standard-errors-r
#Need this for clustered standard errors
clse.f <- function(dat,fm, cluster){
 require(sandwich)
 require(lmtest)
 not <- attr(fm$model,"na.action")
if( ! is.null(not)){
  cluster <- cluster[-not]
    dat <- dat[-not,]
}
 with(dat,{
 M <- length(unique(cluster))
 N <- length(cluster)
 K <- fm$rank
 dfc <- (M/(M-1))*((N-1)/(N-K))
 uj <- apply(estfun(fm),2, function(x) tapply(x, cluster, sum));
 vcovCL <- dfc*sandwich(fm, meat=crossprod(uj)/N)
 coeftest(fm, vcovCL)
 }
 )
}

data_matrix=data_matrix[,-c(grep(names(data_matrix),pattern='scores'))]
candidate_matrix=cbind(data_matrix,scored[,c('scores','scores_var','scores_policy','scores_policy_var')])

# i_policy is conjoint position in either i1 or i2
# consistency here is candidate too consistent Dem or Rep position on policy
# analogous to above variance in aggregating over candidate profiles on issues

candidate_matrix$consistency=
as.numeric(candidate_matrix$"i_lgbt"==1)*-1+
as.numeric(candidate_matrix$"i_marriage"==1)*1+
as.numeric(candidate_matrix$"i_need"==1)*-1+
as.numeric(candidate_matrix$"i_govabuse"==1)*1+
as.numeric(candidate_matrix$"i_freetrade"==1)*-1+
as.numeric(candidate_matrix$"i_unfairtrade"==1)*1+
as.numeric(candidate_matrix$"i_righttochoose"==1)*-1+
as.numeric(candidate_matrix$"i_unbornlives"==1)*1+
as.numeric(candidate_matrix$"i_raisetaxes"==1)*-1+
as.numeric(candidate_matrix$"i_cuttaxes"==1)*1+
as.numeric(candidate_matrix$"i_co2emissions"==1)*-1+
as.numeric(candidate_matrix$"i_drilling"==1)*1+
as.numeric(candidate_matrix$"i_citizenship"==1)*-1+
as.numeric(candidate_matrix$"i_bordersecurity"==1)*1+
as.numeric(candidate_matrix$"i_guncontrol"==1)*-1+
as.numeric(candidate_matrix$"i_gunrights"==1)*1+
as.numeric(candidate_matrix$"i_reducemilitary"==1)*-1+
as.numeric(candidate_matrix$"i_strengthenmilitary"==1)*1+
as.numeric(candidate_matrix$"i_policing"==1)*-1+
as.numeric(candidate_matrix$"i_criminals"==1)*1


candidate_matrix$libcon=rowMeans(cbind(candidate_matrix[,grep(names(candidate_matrix),pattern='libcon')],candidate_matrix$self_place/3))


############################################################
############################################################
###Now for Primary Elections (by PID)  -  InParty
############################################################
############################################################
###Now for Primary Elections (by PID)  -  OutParty

load('data/issueCrossPressureData.Rdata')

voter_id=unique(candidate_matrix$respondent)
voter_matrix=as.data.frame(matrix(NA,length(voter_id),ncol(candidate_matrix)))
for(i in 1:length(voter_id)){
  ix=which(candidate_matrix$respondent==voter_id[i])[1]
  voter_matrix[i,]=candidate_matrix[ix,]
}
names(voter_matrix)=names(candidate_matrix)
# identify rank order of which components correlate with summary w/n each dimension
# which items are more consistently answered



# inference-type approach; pick strongest interactions among items in support * policy-specific conjoint items
#c("envs_policy1","envs_policy2","envs_policy3","envs_policy4",
#"crme_policy1","crme_policy2","crme_policy3","crme_policy4",
#"abrt_policy1","abrt_policy2","abrt_policy3","abrt_policy4","abrt_policy5","abrt_policy6",
#"gays_policy1","gays_policy1",
#"immi_policy1","immi_policy2","immi_policy3","immi_policy4","immi_policy5","immi_policy6","immi_policy7","immi_policy7",
#"roll_tpp_act","roll_trd_adj",
#"guns_policy1","guns_policy2","guns_policy3","guns_policy4",
#"dfns_policy2","roll_usa_fre","roll_iransct",
#"roll_educrfr","roll_infrast","roll_medicar","roll_rpl_aca","roll_minwage")

# frequency of mis-classifications across issues
id=which(voter_matrix$pid==-1)
ir=which(voter_matrix$pid==1)
xmu=c(as.numeric(voter_matrix$libcon_envs[id]>0)+
as.numeric(voter_matrix$libcon_crme[id]>0)+
as.numeric(voter_matrix$libcon_abrt[id]>0)+
as.numeric(voter_matrix$libcon_gays[id]>0)+
as.numeric(voter_matrix$libcon_immi[id]>0)+
as.numeric(voter_matrix$libcon_trad[id]>0)+
as.numeric(voter_matrix$libcon_guns[id]>0)+
as.numeric(voter_matrix$libcon_dfns[id]>0)+
as.numeric(voter_matrix$libcon_taxs[id]>0)+
as.numeric(voter_matrix$libcon_need[id]>0),
as.numeric(voter_matrix$libcon_envs[ir]<0)+
as.numeric(voter_matrix$libcon_crme[ir]<0)+
as.numeric(voter_matrix$libcon_abrt[ir]<0)+
as.numeric(voter_matrix$libcon_gays[ir]<0)+
as.numeric(voter_matrix$libcon_immi[ir]<0)+
as.numeric(voter_matrix$libcon_trad[ir]<0)+
as.numeric(voter_matrix$libcon_guns[ir]<0)+
as.numeric(voter_matrix$libcon_dfns[ir]<0)+
as.numeric(voter_matrix$libcon_taxs[ir]<0)+
as.numeric(voter_matrix$libcon_need[ir]<0))

ymu=c(as.numeric(voter_matrix$libcon_envs[id]<0)+
as.numeric(voter_matrix$libcon_crme[id]<0)+
as.numeric(voter_matrix$libcon_abrt[id]<0)+
as.numeric(voter_matrix$libcon_gays[id]<0)+
as.numeric(voter_matrix$libcon_immi[id]<0)+
as.numeric(voter_matrix$libcon_trad[id]<0)+
as.numeric(voter_matrix$libcon_guns[id]<0)+
as.numeric(voter_matrix$libcon_dfns[id]<0)+
as.numeric(voter_matrix$libcon_taxs[id]<0)+
as.numeric(voter_matrix$libcon_need[id]<0),
as.numeric(voter_matrix$libcon_envs[ir]>0)+
as.numeric(voter_matrix$libcon_crme[ir]>0)+
as.numeric(voter_matrix$libcon_abrt[ir]>0)+
as.numeric(voter_matrix$libcon_gays[ir]>0)+
as.numeric(voter_matrix$libcon_immi[ir]>0)+
as.numeric(voter_matrix$libcon_trad[ir]>0)+
as.numeric(voter_matrix$libcon_guns[ir]>0)+
as.numeric(voter_matrix$libcon_dfns[ir]>0)+
as.numeric(voter_matrix$libcon_taxs[ir]>0)+
as.numeric(voter_matrix$libcon_need[ir]>0))

names(xmu)=c(id,ir)
names(ymu)=c(id,ir)

# kinder and kalmoe + identify the 20-30% who score highest on ideological knowledge/consistency
k_gov=voter_matrix$know_gov
k_sen1=voter_matrix$know_senate1
k_sen2=voter_matrix$know_senate2

k_gov[which(voter_matrix$know_gov=='Republican')]=1
k_gov[grep(voter_matrix$know_gov,pattern='Independent')]=0
k_gov[which(voter_matrix$know_gov=='Democrat')]=-1
k_gov[!grepl(k_gov,pattern='[0,1]')]=-2

k_sen1[which(voter_matrix$know_senate1=='Republican')]=1
k_sen1[grep(voter_matrix$know_senate1,pattern='Independent')]=0
k_sen1[which(voter_matrix$know_senate1=='Democrat')]=-1
k_sen1[!grepl(k_sen1,pattern='[0,1]')]=-2

k_sen2[which(voter_matrix$know_senate2=='Republican')]=1
k_sen2[grep(voter_matrix$know_senate2,pattern='Independent')]=0
k_sen2[which(voter_matrix$know_senate2=='Democrat')]=-1
k_sen2[!grepl(k_sen2,pattern='[0,1]')]=-2

k_gov=as.numeric(k_gov)
k_sen1=as.numeric(k_sen1)
k_sen2=as.numeric(k_sen2)

sen2=sign(tapply(k_sen2[which(k_sen2> -2)],voter_matrix$state[which(k_sen2> -2)],mean,na.rm=T)) # sanders and angus king
sen2[which(names(sen2)=='Wyoming')]=1
sen2[which(names(sen2)=='Vermont')]=0
sen2[which(names(sen2)=='Maine')]=0
sen1=sign(tapply(k_sen1[which(k_sen1> -2)],voter_matrix$state[which(k_sen1> -2)],mean,na.rm=T))
gov=sign(tapply(k_gov[which(k_gov> -2)],voter_matrix$state[which(k_gov> -2)],mean,na.rm=T))

know_gov=know_senate2=know_senate1=array('Democrat',nrow(voter_matrix))
un_state=unique(voter_matrix$state)
for(j in 1:length(un_state)){
	if(un_state[j]!="District of Columbia"){

		ix=which(voter_matrix$state==un_state[j])

		if(gov[which(names(gov)==un_state[j])]==1){
			know_gov[ix]='Republican'
		}
		if(gov[which(names(gov)==un_state[j])]==0){
			know_gov[ix]='Other Party / Independent'
		}

		if(sen1[which(names(sen1)==un_state[j])]==1){
			know_senate1[ix]='Republican'
		}
		if(sen1[which(names(sen1)==un_state[j])]==0){
			know_senate1[ix]='Other Party / Independent'
		}

		if(sen2[which(names(sen2)==un_state[j])]==1){
			know_senate2[ix]='Republican'
		}
		if(sen2[which(names(sen2)==un_state[j])]==0){
			know_senate2[ix]='Other Party / Independent'
		}

	}
}


# knowledge battery
X=cbind(as.numeric(voter_matrix$know_senate1==know_senate1), 	# know party of sen1
as.numeric(voter_matrix$know_senate2==know_senate2),					# know party of sen2
as.numeric(voter_matrix$know_gov==know_gov),									# know party of gov
as.numeric(voter_matrix$us_house_majority=='Republicans'),		# know house majority
as.numeric(voter_matrix$us_senate_majority=='Republicans'),		# know senate majority
as.numeric(voter_matrix$self_place_attempt==1),								# attempt self place
as.numeric(voter_matrix$dem_place<voter_matrix$rep_place))		# place dems left of reps

colnames(X)=c('know_sen1','know_sen2','know_gov','know_house_maj','know_sen_maj','know_any_self_place','know_D_left_R')

load('data/sophistication_indices.Rdata')


# three level knowledg: 6-7,3-5,0-2
L_ix2=indices$resp_id[indices$"L_ix2"]
M_ix2=indices$resp_id[indices$"M_ix2"]
H_ix2=indices$resp_id[indices$"H_ix2"]

voter_matrix$sophisticated_level=NA
for(i in 1:length(L_ix2)){
	iq=which(L_ix2[i]==voter_matrix$respondent)
	voter_matrix$sophisticated_level[iq]='L'
}
for(i in 1:length(M_ix2)){
	iq=which(M_ix2[i]==voter_matrix$respondent)
	voter_matrix$sophisticated_level[iq]='M'
}
for(i in 1:length(H_ix2)){
	iq=which(H_ix2[i]==voter_matrix$respondent)
	voter_matrix$sophisticated_level[iq]='H'
}

voter_matrix$nonvalidated=as.numeric(voter_matrix$valid_primary==0 & voter_matrix$valid_general==0)
covars=voter_matrix[,c("male","female","white","black","hisps","religion_none","religion_catholic","religion_protestant","religion_evangelical","valid_primary","valid_general","nonvalidated")]

Dmat_sum=round(
	t(rbind(
		c(sum(voter_matrix$pid==-1 & voter_matrix$sophisticated_level=='H'),colSums(covars[which(voter_matrix$pid==-1 & voter_matrix$sophisticated_level=='H'),])),
		c(sum(voter_matrix$pid==-1 & voter_matrix$sophisticated_level=='M'),colSums(covars[which(voter_matrix$pid==-1 & voter_matrix$sophisticated_level=='M'),])),
		c(sum(voter_matrix$pid==-1 & voter_matrix$sophisticated_level=='L'),colSums(covars[which(voter_matrix$pid==-1 & voter_matrix$sophisticated_level=='L'),]))
)))
rownames(Dmat_sum)[1]='all'

Rmat_sum=round(
	t(rbind(
		c(sum(voter_matrix$pid==1 & voter_matrix$sophisticated_level=='H'),colSums(covars[which(voter_matrix$pid==1 & voter_matrix$sophisticated_level=='H'),])),
		c(sum(voter_matrix$pid==1 & voter_matrix$sophisticated_level=='M'),colSums(covars[which(voter_matrix$pid==1 & voter_matrix$sophisticated_level=='M'),])),
		c(sum(voter_matrix$pid==1 & voter_matrix$sophisticated_level=='L'),colSums(covars[which(voter_matrix$pid==1 & voter_matrix$sophisticated_level=='L'),]))
)))
rownames(Rmat_sum)[1]='all'
Dmat=Dmat_sum/rowSums(Dmat_sum)
Rmat=Rmat_sum/rowSums(Rmat_sum)


library(xtable)
txt_tab=cbind(Rmat_sum,Dmat_sum)
num_tab=round(cbind(Rmat,Dmat),digits=2)
for(i in 1:nrow(txt_tab)){
	for(j in 1:ncol(txt_tab)){
		txt_tab[i,j]=paste(sep='',txt_tab[i,j],' (',num_tab[i,j],')')
	}
}
print(xtable(txt_tab,digits=0),file='appendix/figures/descriptives_sophistication_by_pid.tex')

###
# put heterogeneity stuff now, move latere

load('data/sophistication_indices.Rdata')

# three level knowledg: 6-7,3-5,0-2
L_ix2=indices$resp_id[indices$"L_ix2"]
M_ix2=indices$resp_id[indices$"M_ix2"]
H_ix2=indices$resp_id[indices$"H_ix2"]

candidate_matrix$sophisticated_level=NA
for(i in 1:length(L_ix2)){
	iq=which(L_ix2[i]==candidate_matrix$respondent)
	candidate_matrix$sophisticated_level[iq]=0
}
for(i in 1:length(M_ix2)){
	iq=which(M_ix2[i]==candidate_matrix$respondent)
	candidate_matrix$sophisticated_level[iq]=1
}
for(i in 1:length(H_ix2)){
	iq=which(H_ix2[i]==candidate_matrix$respondent)
	candidate_matrix$sophisticated_level[iq]=2
}


candidate_matrix$nonvalidated=as.numeric(candidate_matrix$valid_primary==0 & candidate_matrix$valid_general==0)
library(grf)

vote <- subset(candidate_matrix,(candidate_matrix$conjoints==3|candidate_matrix$conjoints==8))
vote$pty <- ifelse(vote$conjoints==3,0,1)

reps <- subset(vote, vote$pid3==1)
dems <- subset(vote, vote$pid3==-1)


Rcovars=reps[,c("pid3","male","female","white","black","hisps",
	"religion_none","religion_catholic","religion_protestant","religion_evangelical",
	"single","divorced","retired","unemploy",
	"health_insured","aca_insured","media_interest",
	"libcon_envs","libcon_crme","libcon_abrt","libcon_gays",
	"libcon_immi","libcon_trad","libcon_guns",
	"libcon_dfns","libcon_taxs","libcon_need",
	"valid_primary","valid_general","nonvalidated","sophisticated_level"
)]
RTr=reps[,c("g_female","re_black","re_hispanic",
	"r_catholic","r_evangelical","r_protestant",
	"o_ceo","o_citycouncil","o_factoryforeman","o_farmer","o_usarmymajor","o_politicalstaffer","o_smallbizowner","o_stateleg","o_teacher",
	"p_compassionate","p_empathetic","p_inspiring","p_intelligent","p_knowledgeable","p_moral","p_strongleader",
	"e_business","e_christian","e_civilrights","e_energy","e_environment","e_guncontrol","e_gunrights","e_laborunions","e_reproductive","e_taxreform","e_teaparty","e_veterans",
	"rec_refuse","rec_secure","rec_stand","rec_work",
	"i_raisetaxes","i_cuttaxes","i_lgbt","i_marriage","i_drilling","i_need","i_govabuse","i_righttochoose","i_gunrights","i_unfairtrade","i_unbornlives",
	"i_citizenship","i_reducemilitary","i_policing","i_co2emissions","i_bordersecurity","i_guncontrol","i_strengthenmilitary","i_criminals"
)]
Ry=reps$dv_choice

Dcovars=dems[,c("pid3","male","female","white","black","hisps",
	"religion_none","religion_catholic","religion_protestant","religion_evangelical",
	"single","divorced","retired","unemploy",
	"health_insured","aca_insured","media_interest",
	"libcon_envs","libcon_crme","libcon_abrt","libcon_gays",
	"libcon_immi","libcon_trad","libcon_guns",
	"libcon_dfns","libcon_taxs","libcon_need",
	"valid_primary","valid_general","nonvalidated","sophisticated_level"
)]
DTr=dems[,c("g_female","re_black","re_hispanic",
	"r_catholic","r_evangelical","r_protestant",
	"o_ceo","o_citycouncil","o_factoryforeman","o_farmer","o_usarmymajor","o_politicalstaffer","o_smallbizowner","o_stateleg","o_teacher",
	"p_compassionate","p_empathetic","p_inspiring","p_intelligent","p_knowledgeable","p_moral","p_strongleader",
	"e_business","e_christian","e_civilrights","e_energy","e_environment","e_guncontrol","e_gunrights","e_laborunions","e_reproductive","e_taxreform","e_teaparty","e_veterans",
	"rec_refuse","rec_secure","rec_stand","rec_work",
	"i_raisetaxes","i_cuttaxes","i_lgbt","i_marriage","i_drilling","i_need","i_govabuse","i_righttochoose","i_gunrights","i_unfairtrade","i_unbornlives",
	"i_citizenship","i_reducemilitary","i_policing","i_co2emissions","i_bordersecurity","i_guncontrol","i_strengthenmilitary","i_criminals"
)]
Dy=dems$dv_choice

labels <- c(
"Gender - Female vs. Male",
"Race - Black vs. White",
"Race - Hispanic vs. White",
"Religion - Catholic vs. None",
"Religion - Evangelical vs. None",
"Religion - Protestant vs. None",
"Occupation - CEO vs. Attorney",
"Occupation - City Council Member vs. Attorney",
"Occupation - Factory Foreman vs. Attorney",
"Occupation - Farmer vs. Attorney",
"Occupation - Former US Army Major vs. Attorney",
"Occupation - Political Staffer vs. Attorney",
"Occupation - Small Business Owner vs. Attorney",
"Occupation - State Legislator vs. Attorney",
"Occupation - Teacher vs. Attorney",
"Personality - Compassionate vs. Decent",
"Personality - Empathetic vs. Decent",
"Personality - Inspiring vs. Decent",
"Personality - Intelligent vs. Decent",
"Personality - Knowledgeable vs. Decent",
"Personality - Moral vs. Decent",
"Personality - Strong Leader vs. Decent",
"Endorsements - Business groups vs. Major area newspapers",
"Endorsements - Christian groups vs. Major area newspapers",
"Endorsements - Civil rights groups vs. Major area newspapers",
"Endorsements - Energy groups vs. Major area newspapers",
"Endorsements - Environmental groups vs. Major area newspapers",
"Endorsements - Gun control groups vs. Major area newspapers",
"Endorsements - Gun rights groups vs. Major area newspapers",
"Endorsements - Labor unions vs. Major area newspapers",
"Endorsements - Reproductive rights groups vs. Major area newspapers",
"Endorsements - Tax reform groups vs. Major area newspapers",
"Endorsements - Tea Party groups vs. Major area newspapers",
"Endorsements - Veterans groups vs. Major area newspapers",
"Record - Refuse to compromise vs. Help my constituents",
"Record - Secure powerful committee vs. Help my constituents",
"Record - Stand with party vs. Help my constituents",
"Record - Work across the aisle vs. Help my constituents",
"Issue - Raise taxes vs. Free trade",
"Issue - Cut taxes vs. Free trade",
"Issue - LGBT rights vs. Free trade",
"Issue - Traditional marriage vs. Free trade",
"Issue - Expand drilling vs. Free trade",
"Issue - Expand government assistance vs. Free trade",
"Issue - Prevent abuse of assistance programs vs. Free trade",
"Issue - Protect woman's right to choose vs. Free trade",
"Issue - Protect gun owners' rights vs. Free trade",
"Issue - Oppose unfair trade vs. Free trade",
"Issue - Protect the unborn vs. Free trade",
"Issue - Path to citizenship vs. Free trade",
"Issue - Reduce size of military vs. Free trade",
"Issue - Reform policing vs. Free trade",
"Issue - Regulate CO2 emissions vs. Free trade",
"Issue - Strengthen border security vs. Free trade",
"Issue - Strengthen gun control vs. Free trade",
"Issue - Strengthen our military vs. Free trade",
"Issue - Toughen criminal sentences vs. Free trade")

do.choice=T
if(do.choice==T){
# some sort of loop, by parts
for(i in 1:length(labels)){
	#Rs
	W=RTr[,i]
	Y=Ry
	X=cbind(Rcovars,RTr[,-c(i)])
	if(sum(W)>0){
		tau.forest <- causal_forest(X, Y, W)

		tau.hat.oob <- predict(tau.forest)
		x=hist(tau.hat.oob$predictions,breaks=20);dev.off()
		pdf(paste('appendix/figures/R',names(RTr)[i],'.pdf',sep=''))
		cuts=cut(x$breaks, c(-Inf,-.001,0.001,Inf))
		plot(x, col=c("lightgrey","white")[cuts],main=paste('Rep:',labels[i]),xlim=c(-.3,.3),xlab='Distribution of Estimated Treatment Effects')
		#hist(tau.hat.oob$predictions,main=labels[i],xlim=c(-.3,.3),xlab='Distribution of Estimated Treatment Effects')
		abline(v=mean(tau.hat.oob$predictions),col='red',lty=2,lwd=2)
		dev.off()
	} else{
		pdf(paste('appendix/figures/R',names(RTr)[i],'.pdf',sep=''))
		#cuts=cut(x$breaks, c(-Inf,-.001,0.001,Inf))
		plot(axes=F,-1000,1000, main=paste('Rep:',labels[i]),xlim=c(-.3,.3),ylim=c(0,10),ylab='Frequency',xlab='Distribution of Estimated Treatment Effects')
		#hist(tau.hat.oob$predictions,main=labels[i],xlim=c(-.3,.3),xlab='Distribution of Estimated Treatment Effects')
		#bline(v=mean(tau.hat.oob$predictions),col='red',lty=2,lwd=2)
		axis(1,)
		axis(2,)
		dev.off()
	}

	#Ds
	W=DTr[,i]
	Y=Dy
	X=cbind(Dcovars,DTr[,-c(i)])
	if(sum(W)>0){
		tau.forest <- causal_forest(X, Y, W)

		tau.hat.oob <- predict(tau.forest)
		x=hist(tau.hat.oob$predictions,breaks=20);dev.off()
		pdf(paste('appendix/figures/D',names(DTr)[i],'.pdf',sep=''))
		cuts=cut(x$breaks, c(-Inf,-.001,0.001,Inf))
		plot(x, col=c("lightgrey","white")[cuts],main=paste('Dem:',labels[i]),xlim=c(-.3,.3),xlab='Distribution of Estimated Treatment Effects')
		#hist(tau.hat.oob$predictions,main=labels[i],xlim=c(-.3,.3),xlab='Distribution of Estimated Treatment Effects')
		abline(v=mean(tau.hat.oob$predictions),col='red',lty=2,lwd=2)
		dev.off()
	} else{
		pdf(paste('appendix/figures/D',names(DTr)[i],'.pdf',sep=''))
		#cuts=cut(x$breaks, c(-Inf,-.001,0.001,Inf))
		plot(axes=F,-1000,1000,main=paste('Dem:',labels[i]),xlim=c(-.3,.3),ylim=c(0,10),ylab='Frequency',xlab='Distribution of Estimated Treatment Effects')
		#hist(tau.hat.oob$predictions,main=labels[i],xlim=c(-.3,.3),xlab='Distribution of Estimated Treatment Effects')
		#abline(v=mean(tau.hat.oob$predictions),col='red',lty=2,lwd=2)
		axis(1,)
		axis(2,)
		dev.off()
	}
}
}


vote <- subset(candidate_matrix,(candidate_matrix$conjoints==1|candidate_matrix$conjoints==2|candidate_matrix$conjoints==5|candidate_matrix$conjoints==6))

#Standardizing the direction across 1,2,5,6 JAHconjoints w/ Lib = 0, Cons = 1
vote$dv_libcon <- ifelse(
vote$conjoints==1& vote$dv_choice==1,0,ifelse(
vote$conjoints==1& vote$dv_choice==0,1,ifelse(
vote$conjoints==5& vote$dv_choice==1,0,ifelse(
vote$conjoints==5& vote$dv_choice==0,1,ifelse(
vote$conjoints==2& vote$dv_choice==1,1,ifelse(
vote$conjoints==2& vote$dv_choice==0,0,ifelse(
vote$conjoints==6& vote$dv_choice==1,1,ifelse(
vote$conjoints==6& vote$dv_choice==0,0,NA))))))))

vote$pty <- ifelse(vote$conjoints==1 | vote$conjoints==5,0,1)
#reps <- subset(vote, vote$pid3==1)
#dems <- subset(vote, vote$pid3==-1)


covars=vote[,c("pty","pid3","male","female","white","black","hisps",
	"religion_none","religion_catholic","religion_protestant","religion_evangelical",
	"single","divorced","retired","unemploy",
	"health_insured","aca_insured","media_interest",
	"libcon_envs","libcon_crme","libcon_abrt","libcon_gays",
	"libcon_immi","libcon_trad","libcon_guns",
	"libcon_dfns","libcon_taxs","libcon_need",
	"valid_primary","valid_general","nonvalidated","sophisticated_level"
)]
Tr=vote[,c("g_female","re_black","re_hispanic",
	"r_catholic","r_evangelical","r_protestant",
	"o_ceo","o_citycouncil","o_factoryforeman","o_farmer","o_usarmymajor","o_politicalstaffer","o_smallbizowner","o_stateleg","o_teacher",
	"p_compassionate","p_empathetic","p_inspiring","p_intelligent","p_knowledgeable","p_moral","p_strongleader",
	"e_business","e_christian","e_civilrights","e_energy","e_environment","e_guncontrol","e_gunrights","e_laborunions","e_reproductive","e_taxreform","e_teaparty","e_veterans",
	"rec_refuse","rec_secure","rec_stand","rec_work",
	"i_raisetaxes","i_cuttaxes","i_lgbt","i_marriage","i_drilling","i_need","i_govabuse","i_righttochoose","i_gunrights","i_unfairtrade","i_unbornlives",
	"i_citizenship","i_reducemilitary","i_policing","i_co2emissions","i_bordersecurity","i_guncontrol","i_strengthenmilitary","i_criminals"
)]
y=vote$dv_libcon

labels <- c(
"Gender - Female vs. Male",
"Race - Black vs. White",
"Race - Hispanic vs. White",
"Religion - Catholic vs. None",
"Religion - Evangelical vs. None",
"Religion - Protestant vs. None",
"Occupation - CEO vs. Attorney",
"Occupation - City Council Member vs. Attorney",
"Occupation - Factory Foreman vs. Attorney",
"Occupation - Farmer vs. Attorney",
"Occupation - Former US Army Major vs. Attorney",
"Occupation - Political Staffer vs. Attorney",
"Occupation - Small Business Owner vs. Attorney",
"Occupation - State Legislator vs. Attorney",
"Occupation - Teacher vs. Attorney",
"Personality - Compassionate vs. Decent",
"Personality - Empathetic vs. Decent",
"Personality - Inspiring vs. Decent",
"Personality - Intelligent vs. Decent",
"Personality - Knowledgeable vs. Decent",
"Personality - Moral vs. Decent",
"Personality - Strong Leader vs. Decent",
"Endorsements - Business groups vs. Major area newspapers",
"Endorsements - Christian groups vs. Major area newspapers",
"Endorsements - Civil rights groups vs. Major area newspapers",
"Endorsements - Energy groups vs. Major area newspapers",
"Endorsements - Environmental groups vs. Major area newspapers",
"Endorsements - Gun control groups vs. Major area newspapers",
"Endorsements - Gun rights groups vs. Major area newspapers",
"Endorsements - Labor unions vs. Major area newspapers",
"Endorsements - Reproductive rights groups vs. Major area newspapers",
"Endorsements - Tax reform groups vs. Major area newspapers",
"Endorsements - Tea Party groups vs. Major area newspapers",
"Endorsements - Veterans groups vs. Major area newspapers",
"Record - Refuse to compromise vs. Help my constituents",
"Record - Secure powerful committee vs. Help my constituents",
"Record - Stand with party vs. Help my constituents",
"Record - Work across the aisle vs. Help my constituents",
"Issue - Raise taxes vs. Free trade",
"Issue - Cut taxes vs. Free trade",
"Issue - LGBT rights vs. Free trade",
"Issue - Traditional marriage vs. Free trade",
"Issue - Expand drilling vs. Free trade",
"Issue - Expand government assistance vs. Free trade",
"Issue - Prevent abuse of assistance programs vs. Free trade",
"Issue - Protect woman's right to choose vs. Free trade",
"Issue - Protect gun owners' rights vs. Free trade",
"Issue - Oppose unfair trade vs. Free trade",
"Issue - Protect the unborn vs. Free trade",
"Issue - Path to citizenship vs. Free trade",
"Issue - Reduce size of military vs. Free trade",
"Issue - Reform policing vs. Free trade",
"Issue - Regulate CO2 emissions vs. Free trade",
"Issue - Strengthen border security vs. Free trade",
"Issue - Strengthen gun control vs. Free trade",
"Issue - Strengthen our military vs. Free trade",
"Issue - Toughen criminal sentences vs. Free trade")

do.place=T
if(do.place==T){
# some sort of loop, by parts
for(i in 1:length(labels)){
	#Rs
	W=Tr[,i]
	Y=y
	X=cbind(covars,Tr[,-c(i)])
	if(sum(W)>0){
		tau.forest <- causal_forest(X, Y, W)

		tau.hat.oob <- predict(tau.forest)
		x=hist(tau.hat.oob$predictions,breaks=20);dev.off()
		pdf(paste('appendix/figures/All',names(Tr)[i],'_libcon.pdf',sep=''))
		cuts=cut(x$breaks, c(-Inf,-.001,0.001,Inf))
		plot(x, col=c("lightgrey","white")[cuts],main=paste('All:',labels[i]),xlim=c(-.3,.3),xlab='Distribution of Estimated Treatment Effects')
		#hist(tau.hat.oob$predictions,main=labels[i],xlim=c(-.3,.3),xlab='Distribution of Estimated Treatment Effects')
		abline(v=mean(tau.hat.oob$predictions),col='red',lty=2,lwd=2)
		dev.off()
	} else{
		pdf(paste('appendix/figures/All',names(Tr)[i],'_libcon.pdf',sep=''))
		#cuts=cut(x$breaks, c(-Inf,-.001,0.001,Inf))
		plot(axes=F,-1000,1000, main=paste('All:',labels[i]),xlim=c(-.3,.3),ylim=c(0,10),ylab='Frequency',xlab='Distribution of Estimated Treatment Effects')
		#hist(tau.hat.oob$predictions,main=labels[i],xlim=c(-.3,.3),xlab='Distribution of Estimated Treatment Effects')
		#bline(v=mean(tau.hat.oob$predictions),col='red',lty=2,lwd=2)
		axis(1,)
		axis(2,)
		dev.off()
	}

}
}
#END
